package com.demo.kafka.dongli.config;

import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class KafkaConfig {

    @Value("${spring.kafka.bootstrap-servers}")
    private String bootstrapServers;

    @Value("${spring.kafka.producer.key-serializer}")
    private String keySerializer;

    @Value("${spring.kafka.producer.value-serializer}")
    private String valueSerializer;

    /**
     * 自定义分区策略-生产者相关配置
     *
     * @return
     */
    public Map<String, Object> producerConfigs() {
        Map<String, Object> props = new HashMap<>();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, keySerializer);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, valueSerializer);
        props.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, CustomerPartitioner.class.getName());
        //添加一个拦截器
        props.put(ProducerConfig.INTERCEPTOR_CLASSES_CONFIG, CustomerProducerInterceptor.class.getName());
        return props;
    }

    /**
     * 自定义分区策略-生产者创建工厂
     *
     * @return
     */
    public ProducerFactory<String, ?> producerFactory() {
        return new DefaultKafkaProducerFactory<>(producerConfigs());
    }

    /**
     * 自定义分区策略- kafkaTemplate 覆盖默认配置类中的kafkaTemplate
     * @return
     */
    @Bean
    @Qualifier("customerPartitioner")
    public KafkaTemplate<String, ?> kafkaTemplate() {
        return new KafkaTemplate<>(producerFactory());
    }

    /**
     * 通过代码方式指定分区 和副本  如果是单节点 则副本为1 副本数不能超过节点数 也不能为0
     * @return
     */
    @Bean
    public NewTopic newTopic() {
        return new NewTopic("codeTopic", 5,  (short)1);
    }

    @Bean
    public NewTopic newBatchTopic() {
        return new NewTopic("batch-topic", 5,  (short)1);
    }

    //对topic进行更新 分区只能增加 无法减少
//    @Bean
//    public NewTopic updateNewTopic() {
//        return new NewTopic("heTopic", 9,  (short)1);
//    }
}
